// 普通数组格式化成树形数据
export function parseDataToTree(obj) {
  let idKey = obj.idKey
    ? obj.idKey
    : 'id'
  let pidKey = obj.pidKey
    ? obj.pidKey
    : 'rid'
  let childrenKey = obj.childrenKey
    ? obj.childrenKey
    : 'children'
  let copyData = obj.data.slice(0)
  let orm = {}
  for (let x = 0; x < obj.data.length; x++) {
    for (let y = 0; y < obj.data.length; y++) {
      let tempData = obj.data
      if (tempData[y][pidKey] === obj.data[x][idKey]) {
        delete copyData[y]
        let tsId = tempData[x][idKey]
        if (typeof orm[tsId] === 'undefined') {
          orm[tsId] = []
        }
        orm[tsId].push(tempData[y])
      }
    }
  }
  let deleteNoneTemp
  let deleteNone = []
  for (let x = 0; x < copyData.length; x++) {
    deleteNoneTemp = copyData[x]
    if (typeof deleteNoneTemp !== 'undefined') {
      deleteNone.push(deleteNoneTemp)
    }
  }
  let final = []
  let doOrm = function (obj, orm, idKey) {
    if (orm[obj[idKey]]) {
      let tempO = orm[obj[idKey]]
      for (let x = 0; x < tempO.length; x++) {
        doOrm(tempO[x], orm, idKey)
      }
      obj[childrenKey] = tempO
    }
  }
  for (let index in deleteNone) {
    let _object = deleteNone[index]
    doOrm(_object, orm, idKey)
    final.push(_object)
  }
  return final
}

// 深复制
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'shallowClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  for (const keys in source) {
    if (source.hasOwnProperty(keys)) {
      if (source[keys] && typeof source[keys] === 'object') {
        targetObj[keys] = source[keys].constructor === Array ? [] : {}
        targetObj[keys] = deepClone(source[keys])
      } else {
        targetObj[keys] = source[keys]
      }
    }
  }
  return targetObj
}

// 操作节流
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}
